<template>
  <el-card class="transactions-section">
    <template #header>
      <div class="card-header">
        <h3>交易记录</h3>
        <div class="transaction-filters">
          <el-select v-model="filterData.type" placeholder="交易类型" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="充值" :value="1"></el-option>
            <el-option label="提现" :value="2"></el-option>
            <el-option label="转账" :value="3"></el-option>
            <el-option label="支付" :value="4"></el-option>
            <el-option label="退款" :value="5"></el-option>
          </el-select>
          
          <el-date-picker
            v-model="filterData.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
          ></el-date-picker>
          
          <el-button type="primary" plain @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
        </div>
      </div>
    </template>
    
    <el-table
      :data="transactions"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
      @row-click="showTransactionDetail"
    >
      <el-table-column prop="tradeNo" label="交易流水号" width="180"></el-table-column>
      <el-table-column prop="tradeTypeName" label="交易类型" width="100">
        <template #default="scope">
          <el-tag :type="getTradeTypeTagType(scope.row.tradeType)">
            {{ scope.row.tradeTypeName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="金额" width="120">
        <template #default="scope">
          <span :class="{'income': isIncome(scope.row), 'expense': !isIncome(scope.row)}">
            {{ isIncome(scope.row) ? '+' : '-' }} {{ formatAmount(scope.row.amount) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="statusName" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ scope.row.statusName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="channelName" label="渠道" width="100"></el-table-column>
      <el-table-column prop="createTime" label="交易时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    
    <!-- 交易详情对话框 -->
    <el-dialog v-model="transactionDetailVisible" title="交易详情" width="500px">
      <div v-if="currentTransaction" class="transaction-detail">
        <div class="transaction-header">
          <el-tag :type="getTradeTypeTagType(currentTransaction.tradeType)" class="transaction-type">
            {{ currentTransaction.tradeTypeName }}
          </el-tag>
          <div class="transaction-amount" :class="{'income': isIncome(currentTransaction), 'expense': !isIncome(currentTransaction)}">
            {{ isIncome(currentTransaction) ? '+' : '-' }} {{ formatAmount(currentTransaction.amount) }}
          </div>
        </div>
        
        <el-divider></el-divider>
        
        <div class="detail-item">
          <span class="detail-label">交易流水号</span>
          <span class="detail-value">{{ currentTransaction.tradeNo }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">交易状态</span>
          <el-tag :type="getStatusTagType(currentTransaction.status)">{{ currentTransaction.statusName }}</el-tag>
        </div>
        <div class="detail-item">
          <span class="detail-label">交易时间</span>
          <span class="detail-value">{{ formatDateTime(currentTransaction.createTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">交易渠道</span>
          <span class="detail-value">{{ currentTransaction.channelName }}</span>
        </div>
        <div class="detail-item" v-if="currentTransaction.targetAccount">
          <span class="detail-label">目标账户</span>
          <span class="detail-value">{{ currentTransaction.targetAccount }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">交易后余额</span>
          <span class="detail-value">{{ formatAmount(currentTransaction.balance) }}</span>
        </div>
        <div class="detail-item" v-if="currentTransaction.remark">
          <span class="detail-label">备注</span>
          <span class="detail-value">{{ currentTransaction.remark }}</span>
        </div>
      </div>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { getTransactionList } from '@/api/account';

const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:loading']);

// 交易记录数据
const transactions = ref([]);
const filterData = reactive({
  type: '',
  dateRange: []
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 当前选中的交易详情
const currentTransaction = ref(null);
const transactionDetailVisible = ref(false);

// 格式化金额
const formatAmount = (amount) => {
  if (amount === undefined || amount === null) return '0.00';
  return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '暂无数据';
  
  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 判断交易类型是否为收入
const isIncome = (transaction) => {
  // 充值和退款是收入
  return transaction.tradeType === 1 || transaction.tradeType === 5;
};

// 获取交易类型对应的标签类型
const getTradeTypeTagType = (tradeType) => {
  const typeMap = {
    1: 'success', // 充值
    2: 'warning', // 提现
    3: 'info',    // 转账
    4: 'danger',  // 支付
    5: 'success'  // 退款
  };
  
  return typeMap[tradeType] || 'info';
};

// 获取交易状态对应的标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    0: 'info',    // 处理中
    1: 'success', // 成功
    2: 'danger'   // 失败
  };
  
  return statusMap[status] || 'info';
};

// 加载交易记录
const loadTransactions = async () => {
  emit('update:loading', true);
  
  try {
    // 构建参数
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    };
    
    // 添加交易类型过滤
    if (filterData.type) {
      params.tradeType = filterData.type;
    }
    
    // 添加日期范围过滤
    if (filterData.dateRange && filterData.dateRange.length === 2) {
      params.startTime = formatDateTime(filterData.dateRange[0]);
      params.endTime = formatDateTime(filterData.dateRange[1]);
    }
    
    const response = await getTransactionList(params);
    if (response.code === 0) {
      transactions.value = response.data || [];
      pagination.total = response.total || 0;
    }
  } catch (error) {
    console.error('获取交易记录失败:', error);
  } finally {
    emit('update:loading', false);
  }
};

// 显示交易详情
const showTransactionDetail = (row) => {
  currentTransaction.value = row;
  transactionDetailVisible.value = true;
};

// 处理查询按钮点击
const handleSearch = () => {
  pagination.currentPage = 1;
  loadTransactions();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  loadTransactions();
};

// 处理当前页码变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  loadTransactions();
};

// 初始加载
loadTransactions();
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.transaction-filters {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.income {
  color: #67c23a;
  font-weight: 600;
}

.expense {
  color: #f56c6c;
  font-weight: 600;
}

.transaction-detail {
  padding: 10px;
}

.transaction-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.transaction-type {
  font-size: 16px;
}

.transaction-amount {
  font-size: 24px;
  font-weight: 700;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-label {
  color: #909399;
  font-size: 14px;
}

.detail-value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

@media (max-width: 768px) {
  .transaction-filters {
    flex-direction: column;
  }
}
</style>
